import React, {
  forwardRef,
  useCallback,
  useContext,
  useImperativeHandle,
  useState,
} from 'react';
import dragOperationSlice from '../redux/toolKitSlice/dragOperation';
import Card from './Card';
import TransferBoxContext from './TransferBoxContext';
import type { RefFn } from './index';

const Right = forwardRef<RefFn>((props, ref) => {
  const { onDeletInsertItem, store } = useContext(TransferBoxContext);
  const [overIndex, setOverIndex] = useState<number>();
  const [cards, setCards] = useState<{ id: number; text: string }[]>([
    {
      id: 4,
      text: 'text4 S1-T0',
    },
    {
      id: 5,
      text: 'text5 S3-T2',
    },
    {
      id: 6,
      text: 'text6 S5-T4',
    },
  ]);

  //删除
  useImperativeHandle(ref, () => ({
    handleDeletItem: (id) => {
      const newCards = cards.filter((carItem) => carItem.id !== id);
      setCards(newCards);
    },
  }));

  //排序
  const handleMoveCard = useCallback<
    (dragIndex: number, hoverIndex: number) => void
  >(
    (dragIndex, hoverIndex) => {
      const dragItem = cards.splice(dragIndex, 1)[0];
      cards.splice(hoverIndex, 0, dragItem);
      // console.log('--dragIndex--hoverIndex--:', dragIndex, hoverIndex);
      const newCards = [...cards];
      console.log(
        '--right--dragIndex--hoverIndex--handleMoveCard--newCards----:',
        dragIndex,
        hoverIndex,
        newCards,
      );
      setCards(newCards);
    },
    [cards],
  );

  //新增
  const handleAddCard = useCallback(
    (inSertItem: any, hoverIndex: number, targetParent: 'left' | 'right') => {
      cards.splice(hoverIndex + 1, 0, inSertItem);
      const newCards = [...cards];
      console.log(
        '--right--inSertItem--hoverIndex--handleAddCard--newCards----:',
        inSertItem,
        hoverIndex,
        newCards,
      );
      setCards(newCards);
      //左边删除
      onDeletInsertItem(inSertItem, targetParent);
    },
    [cards],
  );

  store.subscribe(() => {
    const { dropIndex, dropParentName } =
      store.getState().dragOperationStore ?? {};
    // overIndex = dropIndex;
    // console.log('--Right--store变化--dropIndex--dropParentName--:', dropIndex, dropParentName);
    setOverIndex(dropParentName === 'right' ? dropIndex : undefined);
  });

  const handleDragEnter: React.DragEventHandler<HTMLElement> = (e) => {
    console.log('--right--ul--handleDragEnter--cards--:', cards);
    if (!cards || cards.length <= 0) {
      // 放置完毕，当前Card已经被删除， handleDrop/ handleDragEnd不会执行
      const operationStore = store.getState().dragOperationStore;
      // console.log('--right--ul--operationStore--:', operationStore);
      const { dragSouce } = operationStore;
      setCards([dragSouce]);
      //右边删除
      // setTimeout(() => { //不执行drop事件又会回弹
      onDeletInsertItem(dragSouce, 'right');
      // }, 5000)

      // 还有over执行？？？
      store.dispatch(dragOperationSlice.actions.endDrag({}));
    }
  };

  return (
    <ul className="sort-h5-card-list" onDragEnter={handleDragEnter}>
      {cards.map((card, i) => (
        <Card
          {...card}
          index={i}
          key={card.id}
          store={store}
          parentName="right"
          onMoveCard={handleMoveCard}
          onAddCard={handleAddCard}
          overIndex={overIndex}
        />
      ))}
    </ul>
  );
});

export default Right;
